package com.moli.lumpSugar.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.time.Duration;

@EnableCaching
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
    @Value("${spring.redis.cache.time-to-live:5}") // 默认过期时间为 5 分钟
    private long ttlMinutes;

//    @Bean("caffeineCacheManager")
//    @Primary
//    public CacheManager caffeineCacheManager() {
//        CaffeineCacheManager cacheManager = new CaffeineCacheManager();
//        // 方案一(常用)：定制化缓存Cache
//        cacheManager.setCaffeine(Caffeine.newBuilder()
//                .expireAfterWrite(5, TimeUnit.MINUTES)
//                .initialCapacity(100)
//                .maximumSize(200));
//        return cacheManager;
//    }

    @Bean("redisCacheManager")
    @Primary
    public CacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        // 创建 RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);

        // 创建 RedisCacheConfiguration
        RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(ttlMinutes))  // 设置缓存过期时间
                .disableCachingNullValues()  // 禁止缓存 null 值
                .prefixKeysWith("lumpSugar:");  // 可选，设置缓存前缀

        // 使用 RedisCacheWriter 和 RedisCacheConfiguration 创建 RedisCacheManager
        return RedisCacheManager.builder(redisCacheWriter)
                .cacheDefaults(cacheConfig)  // 设置默认的缓存配置
                .build();
    }

}
